<?php
/**
 * Created by PhpStorm.
 * User: DELL-PC
 * Date: 2018/8/2
 * Time: 22:45
 */

namespace J\Schema\Collection;


use J\Exception;

class Option
{
    /**
     * @var array
     */
    protected $options = [];

    /**
     * @var ICollection
     */
    protected $poem;

    /**
     * Option constructor.
     * @param ICollection $poem
     */
    public function __construct(ICollection $poem)
    {
        $this->poem = $poem;
    }


    public function getOptions()
    {
        return $this->options;
    }

    /**
     * groupBy语句
     *
     * @param string $name
     * @return static
     * @throws \Exception
     */
    public function groupBy($name = null)
    {
        $this->options['group'] = $this->poem->elements()->getElement($name)->getColumnName();
        return $this;
    }

    /**
     * order 语句
     *
     * @param array $names
     * @param bool $asc
     * @return static
     * @throws Exception
     */
    public function orderBy($names, $asc = true)
    {
        foreach (array_complete($names, $asc) as $k => $v) {
            $this->options['order'][$this->poem->elements()
                ->getElement($k)->getColumnName()] = (bool)$v;
        }

        return $this;
    }

    public function top($n)
    {
        $n = (int)$n;
        if ($n > 0) $this->options['limit'] = (int)$n;
        return $this;
    }

    /**
     * @param int $m 起始页数
     * @param int $n 每页条数
     * @return $this
     */
    public function page($m, $n)
    {
        $n = (int)$n;
        if ($n <= 0) return $this;

        $m = (int)$m;
        if($m <= 1) return $this->top($n);

        $this->options['limit'] = [($m-1)*$n, $n];
        return $this;
    }

}